<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-1-8
 * Time: 下午6:00
 * 站点管理
 */
namespace Service\Controller;
use Mcit\Page;
class SiteController extends BaseController {
    //首页
    public function index(){
        $str=strsToArray(session('location'));
        if($str[0] == 110000){
            $map['location'] = array('like','%110000%');
        }elseif($str[0] == 120000){
            $map['location'] = array('like','%120000%');
        }elseif($str[0] == 310000){
            $map['location'] = array('like','%310000%');
        }elseif($str[0] == 500000){
            $map['location'] = array('like','%500000%');
        }else{
            $map['location'] = array('like','%'.$str['1'].'%');
        }
        if(!empty($_GET['current_state'])){
            $map['current_state'] = array('like','%'.I('current_state').'%');
        }
        if(!empty($_GET['name'])){
            $map['name'] = array('like','%'.I('name').'%');
        }
        if(session("location") == (I("location_f_1").",".I('location_s_1'))){
            if(I('location_s_1') == I('location_t_1')-1){
                $location = I('location_f_1').",".I('location_s_1');
            }else{
                $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
            }
            $map['location'] = array('like','%'.$location.'%');
        }
        //分页
        $count = M("plant")->where($map)->count();
        vendor('Mcit.Sys.Page');
        $Page = new Page($count, 20);
        $pageView = $Page->show();
        $this->assign('pageView', $pageView); //发送分页
        $nowPage = isset($_GET['page']) ? $_GET['page'] : 1;
        $plant = M("plant")->where($map)->order("id")->page($nowPage . ',' . $Page->listRows)->select();
//        echo M()->getLastSql();

        //分页结束
        foreach($plant as $k=>$v){
            //将数字的地址转换成文字
            $region = strsToArray($v['location']);
            $regionOne = D("Admin/Region")->where("code='".$region[2]."'")->field("fullname")->find();
            $plant[$k]['location'] = $regionOne['fullname'];
            if(mb_strlen($v['name'],"utf-8") <= 17){
                $plant[$k]['name_text'] = $v['name'];
            }else{
                $plant[$k]['name_text'] = mb_substr($v['name'],0,17,"utf-8")."···";
            }
        }
        //P($plant);
        //$this->china = D("Admin/Region")->getChinaArea();//所有省市区
        $this->china = D("Admin/Region")->getDowntown($str['0']);//当前省下所有市区县
        $this->assign("plant",$plant);
        $this->display();
    }
    //测试方法
    public function test(){
        /*P($_FILES);
        dump($_POST);*/
            //上传
    }
    //添加站点页面
    public function add(){
        if(IS_POST){
//            P($_POST);die;
            $data = $_POST;
                //上传
                $config = array(
                    'maxSize'       =>  3145728, //上传的文件大小限制 (0-不做限制)
                    'exts'          =>  array('jpg', 'gif', 'png', 'jpeg'), //允许上传的文件后缀
                    'autoSub'       =>  true, //自动子目录保存文件
                    'subName'       =>  array('date', 'Y-m-d'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
                    'rootPath'      =>     './Public/', //保存根路径
                    'savePath'      =>  './data/upload/', //保存路径
                    'saveName'      =>  array('uniqid', ''), //上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
                );
                $upload = new \Think\Upload($config); // 实例化上传类
                $info = $upload->upload();
                if (!$info) { // 上传错误提示错误信息
                    //$this->error($upload->getError());
                } else { // 上传成功 获取上传文件信息
                    $photo = $info[photo][savepath].$info[photo][savename];
                }
            $data['photo'] = $photo;
            $data['location'] = $_POST['location_f_1'].",".$_POST['location_s_1'].",".$_POST['location_t_1'];
            //区号start
            if(I('location_f_1') == 110000){
                $data['area_code'] = '010';
            }elseif(I('location_f_1') == 120000){
                $data['area_code'] = '022';
            }elseif(I('location_f_1') == 310000){
                $data['area_code'] = '021';
            }elseif(I('location_f_1') == 500000){
                $data['area_code'] = '023';
            }else{
                $re = M("region")->where("code='".I("location_s_1")."'")->getField("name");
                if(mb_strlen($re,"utf-8") == 3){
                    $re   = mb_substr($re,0,2,"UTF-8");
                }else if(mb_strlen($re,"utf-8") == 4){
                    $re   = mb_substr($re,0,3,"UTF-8");
                }else if(mb_strlen($re,"utf-8") == 5){
                    $re   = mb_substr($re,0,4,"UTF-8");
                }
                $con['city'] = array("like",$re."%");
                $data['area_code'] = M("area_code")->where($con)->getField("area");
            }
            //区号end
            $data['province']   = M("region")->where("code='".$_POST['location_f_1']."'")->getField("name");
            $data['city']       = M("region")->where("code='".$_POST['location_s_1']."'")->getField("name");
            $data['yy_user_id'] = M("fac")->where("fac_login_name='".$_POST['plant_type']."'")->getField("id");
            $result = M('plant')->data($data)->add();
            if($result > 0){
                $this->redirect("Site/index");
            }else{
                $this->error("添加失败，请重试！");
            }
        }
        $this->oper = M("oper")->where(1)->select();
        $this->fac   = M("fac")->where(1)->select();
        $str=strsToArray(session('location'));
        $this->china = D("Admin/Region")->getDowntown($str['0']);
        $this->display();
    }
    //查看详细页
    public function detail(){
        if(IS_GET){
            $plantOne = M("plant")->where("id='".I('id')."'")->find();
            if($plantOne['plant_type'] == 00000000){
                $plantOne['plant_type'] = "未设置";
            }else{
                $plantOne['plant_type'] = M("fac")->where("fac_login_name='".$plantOne['plant_type']."' and fac_login_name <> '00000000'")->getField("fac_name");
            }
            //将数字的地址转换成文字
            $region = strsToArray($plantOne['location']);
            $regionOne = D("Admin/Region")->where("code='".$region[2]."'")->field("fullname")->find();
            $plantOne['location'] = $regionOne['fullname'];
            $plantOne['oper_city'] = M("oper_city")->where("oper_id='".$plantOne['oper_id']."'")->getField("oper_city");
            $plantOne['oper_id'] = M("oper")->where("id='".$plantOne['oper_id']."'")->getField("oper_name");
            $plantOne['booking'] = $plantOne['booking'] == 1 ? 支持:不支持;
            if($plantOne['evc_type'] == 1){
                $plantOne['evc_type'] = "直流";
            }elseif($plantOne['evc_type'] == 2){
                $plantOne['evc_type'] = "交流";
            }else{
                $plantOne['evc_type'] = "混合";
            }
            $plantOne['wifi'] = $plantOne['wifi'] == 1 ? 支持:不支持;
            if($plantOne['floor'] == 1){
                $plantOne['floor'] = "停车楼";
            }elseif($plantOne['floor'] == 2){
                $plantOne['floor'] = "室外";
            }else{
                $plantOne['floor'] = "地下室";
            }
            if($plantOne['charge_port_type'] == 1){
                $plantOne['charge_port_type'] = "国标";
            }elseif($plantOne['charge_port_type'] == 2){
                $plantOne['charge_port_type'] = "特斯拉";
            }elseif($plantOne['charge_port_type'] == 3){
                $plantOne['charge_port_type'] = "ABB";
            }else{
                $plantOne['charge_port_type'] = "其他";
            }
            $this->assign("plant",$plantOne);
        }
        $this->display();
    }
    //修改详细信息
    public function update(){
        if(IS_GET){
            $plant= M("plant")->where("id='".I('id')."'")->find();
            //将数字的地址转换成文字
            $region = strsToArray($plant['location']);
            $region = D("Admin/Region")->where("code='".$region[2]."'")->field("fullname")->find();
            $plant['oper_name'] = M("oper")->where("id='".$plant['oper_id']."'")->getField("oper_name");
            $plant['location_text'] = $region['fullname'];
            $this->assign("plant",$plant);
            $this->assign("region",$region);
            $this->oper = M("oper")->where(1)->select();
            $str=strsToArray(session('location'));
            $this->china = D("Admin/Region")->getDowntown($str['0']);
            $this->fac   = M("fac")->where(1)->select();
        }
        if(IS_POST){
//            P($_POST);die;
            $data = $_POST;
            if($data['location_f'] != 0 && $data['location_s'] != 0 && $data['location_t'] != 0){
                    $data['location'] = $data['location_f'].",".$data['location_s'].",".$data['location_t'];
            }
            if($_FILES['photo']['name'] != ''){
                //上传
                $config = array(
                    'maxSize'       =>  3145728, //上传的文件大小限制 (0-不做限制)
                    'exts'          =>  array('jpg', 'gif', 'png', 'jpeg'), //允许上传的文件后缀
                    'autoSub'       =>  true, //自动子目录保存文件
                    'subName'       =>  array('date', 'Y-m-d'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
                    'rootPath'      =>     './Public/', //保存根路径
                    'savePath'      =>  './data/upload/', //保存路径
                    'saveName'      =>  array('uniqid', ''), //上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
                );
                $upload = new \Think\Upload($config); // 实例化上传类
                $info = $upload->upload();
                if (!$info) { // 上传错误提示错误信息
                    //$this->error($upload->getError());
                } else { // 上传成功 获取上传文件信息
                    $data['photo'] = $info[photo][savepath].$info[photo][savename];
                    if(file_exists($plant['photo'])){
                        unlink($plant['photo']);
                    }
                }
            }
            $result = M("plant")->where("id='".$_POST['id']."'")->save($data);
            if($result > 0){
                $this->redirect("Site/index");
            }else{
                $this->error("添加失败，请重试！");
            }
        }
        $this->display();
    }
    //删除一条数据（同时此站点下的所有电桩信息都将删除）
    public function del(){
        if(IS_GET){
          //删除状态记录数据
          $char = M("char")->where("ev_plant_id='".$_GET['id']."'")->select();
          foreach($char as $v){
              D("Admin/State")->where("key_link='".$v['key_link']."'")->delete();
          }
           //删除电桩表数据
          M("char")->where("ev_plant_id='".$_GET['id']."'")->delete();
          //删除站点图片
            $plant_photo = M("plant")->where("id='".$_GET['id']."'")->getField("photo");
            $plant_url   = APP_ROOT_PATH.'/Public'.$plant_photo;
            unlink($plant_url);
          //删除站点数据
          $result = M("plant")->where("id='".$_GET['id']."'")->delete();
          if($result){
              echo 1;
          }else{
              echo 0;
          }
        }else{
            $ids = strsToArray($_POST['ids']);
            $map['id'] = array("IN",$ids);
            $plant = M("plant")->where($map)->select();
            foreach($plant as $val){
                //删除状态记录数据
                $char = M("char")->where("ev_plant_id='".$val['id']."'")->select();
                foreach($char as $v){
                    D("Admin/State")->where("key_link='".$v['key_link']."'")->delete();
                }
                //删除电桩表数据
                M("char")->where("ev_plant_id='".$val['id']."'")->delete();
                //删除站点图片
                /*$plant_photo = M("plant")->where("id='".$val['id']."'")->getField("photo");
                $plant_url = APP_ROOT_PATH.'/Public'.$plant_photo;*/
                $plant_url = APP_ROOT_PATH.'/Public'.$val['photo'];
                unlink($plant_url);
                //删除站点数据
                $result = M("plant")->where("id='".$val['id']."'")->delete();
            }
            if($result){
                $return['state'] = 100;
                $return['msg']   = '删除成功！';
            }else{
                $return['state'] = 200;
                $return['msg']   = '删除失败！';
            }
            echo json_encode($return);
            exit;
        }
    }
    //站点的建设状态
    public function changehh(){

        $id        = I('id');
        $value     = I('value');
        $map['id'] = $id;
        $data['current_state'] = $value;
        $result    = M('plant')->where($map)->save($data);

        if($result){
            if($value==3){
                $return['html']  = '<a class="btn btn-warning btn-xs changehh" data-id="'.$id.'" data-info="确定将该站点状态修改为“安装中”？" data-value="2">&nbsp;&nbsp;&nbsp;规划中&nbsp;&nbsp;&nbsp;</a>';
                $return['state'] = 300;
                $return['msg']   = '保存成功';
            }elseif($value==2){
                $return['html']  = '<a class="btn btn-warning btn-xs changehh" data-id="'.$id.'" data-info="确定将该站点状态修改为“运营中”？" data-value="1">&nbsp;&nbsp;&nbsp;安装中&nbsp;&nbsp;&nbsp;</a>';
                $return['state'] = 200;
                $return['msg']   = '保存成功';
            }else{
                $return['html']  = '<a class="btn btn-success btn-xs " data-id="'.$id.'" data-info="确定将该站点状态修改为“规划中”？" data-value="3">&nbsp;&nbsp;&nbsp;运营中&nbsp;&nbsp;&nbsp;</a>';
                $return['state'] = 100;
                $return['msg']   = '保存成功';
            }
        }else{
            $return['state'] = 404;
            $return['msg']   = '保存失败';
        }
        echo json_encode($return);

        exit;
    }
    //站点是否支持实时
    public function changeA(){
        $id        = I('aid');
        $value     = I('avalue');
        $map['id'] = $id;
        $data['is_active'] = $value;
        $results    = M("plant")->where($map)->save($data);
        //echo json_encode(M("plant")->getLastSql());
        if($results){
            if($value==1){
                $return['html'] = '<a class="btn  btn-xs changeA" data-value="0"  data-id="'.$id.'" data-info="确定修改为“不支持实时”？"><img src="'.__ROOT__.'/Public/img/gou.png" alt="是"/></a>';
            }else{
                $return['html'] = '<a class="btn  btn-xs changeA" data-value="1"  data-id="'.$id.'" data-info="确定修改为“支持实时”？"><img src="'.__ROOT__.'/Public/img/cha.png" alt="否"/></a>';
            }
            $return['state'] = 100;
            $return['msg']   = '保存成功';
        }else{
            $return['state'] = 200;
            $return['msg']   = '保存失败';
        }
        echo json_encode($return);
        exit;
    }
}
